package utils

import (
	"fmt"
	"github.com/go-redis/redis/v8"
	"github.com/panjf2000/ants/v2"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
	"sync"
	"time"
)

var (
	DB            *gorm.DB
	RDB           *redis.Client
	GoroutinePool *ants.Pool
)

func Init() {
	var wg = sync.WaitGroup{}
	InitConfig()
	InitGoroutinePool()
	wg.Add(1)
	GoroutinePool.Submit(func() {
		defer wg.Done()
		InitMysql()
	})
	wg.Add(1)
	GoroutinePool.Submit(func() {
		defer wg.Done()
		InitRedis()
	})
	wg.Wait()
	fmt.Println("配置加载完成")
}

func InitConfig() {
	viper.SetConfigName("app")
	viper.AddConfigPath("config")
	err := viper.ReadInConfig()
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("配置读取成功")
}

func InitMysql() {
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold: time.Second,
			LogLevel:      logger.Info,
			Colorful:      true,
		},
	)
	db, err := gorm.Open(mysql.Open(viper.GetString("mysql.dns")), &gorm.Config{Logger: newLogger})
	if err != nil {
		panic("failed to connect database")
		return
	}
	DB = db
	fmt.Println("数据库连接成功")
}
func InitRedis() {
	rdb := redis.NewClient(&redis.Options{
		Addr:         viper.GetString("redis.addr"),
		Password:     viper.GetString("redis.password"),
		DB:           viper.GetInt("redis.db"),
		PoolSize:     viper.GetInt("redis.poolSize"),
		MinIdleConns: viper.GetInt("redis.minIdleConn"),
	})
	/*	_, err := rdb.Ping().Result()
		if err != nil {
			panic(err)
			return
		}*/
	RDB = rdb
	fmt.Println("redis连接成功")
}

func RegisterModels(models ...interface{}) error {
	return DB.AutoMigrate(models...)
}

func InitGoroutinePool() {
	pool, err := ants.NewPool(viper.GetInt("goroutinePool.size"))
	if err != nil {
		panic(err)
	}
	GoroutinePool = pool
	fmt.Println("协程池初始化成功")
}
